package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmUserDTO;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.model.wemedia.vos.WmUserVO;
import com.heima.utils.common.AppJwtUtil;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmUserService;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;

/**
 * @author lo
 */
@Service
public class WmUserServiceImpl extends ServiceImpl<WmUserMapper, WmUser> implements WmUserService {
    /**
     * 自媒体端登录
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(WmUserDTO dto) {
        //1.参数校验
        if (Strings.isBlank(dto.getName()) || Strings.isBlank(dto.getPassword())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE, "账户名或者密码不能为空");
        }
        //2.根据用户名查询数据
        WmUser user = this.getOne(Wrappers.<WmUser>lambdaQuery().eq(WmUser::getName, dto.getName()));
        if (user == null){
            //说明没有查询到用户
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"该账户不存在");
        }
        //3.校验密码
        String password = user.getPassword();
        String dtoPassword = dto.getPassword();
        // 将dto中的密码加盐再加密
        String asHex = DigestUtils.md5DigestAsHex((dtoPassword + user.getSalt()).getBytes());
        if (!password.equals(asHex)){
            //说明密码不对
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }

        //4.颁发token
        String token = AppJwtUtil.getToken(Long.valueOf(user.getId()));

        //4.封装返回属性
        HashMap<Object, Object> map = new HashMap<>(8);
        WmUserVO wmUserVO = new WmUserVO();
        BeanUtils.copyProperties(user,wmUserVO);
        wmUserVO.setLoginTime(new Date());

        map.put("token",token);
        map.put("user",wmUserVO);
        return ResponseResult.okResult(map);
    }
}